import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class PrimeNumberFinderPro{
    public static void main(String[] args) {
        int limit = 20000;
        List<Integer> primes = sieveOfEratosthenes(limit);
        printPrimes(primes, 5);
    }
    public static List<Integer> sieveOfEratosthenes(int limit) {
        boolean[] isPrime = new boolean[limit + 1];
        Arrays.fill(isPrime, true);
        if (limit >= 0) isPrime[0] = false;
        if (limit >= 1) isPrime[1] = false;
        for (int p = 2; p * p <= limit; p++) {
            if (isPrime[p]) {
                for (int i = p * p; i <= limit; i += p) {
                    isPrime[i] = false;
                }
            }
        }
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= limit; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
        }
        return primes;
    }
    public static void printPrimes(List<Integer> primes, int countPerLine) {
        int count = 0;
        for (int prime : primes) {
            System.out.printf("%-7d", prime);
            count++;
            if (count % countPerLine == 0) {
                System.out.println();
            }
        }
        if (count % countPerLine != 0) {
            System.out.println();
        }
    }
}
